package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.Result;
import com.itheima.dto.DishDto;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    public Result add(DishDto dishDto) {

        List<DishFlavor> flavors = dishDto.getFlavors();

        dishService.save(dishDto);

        Dish dish = dishService.getById(dishDto);
        Long id = dish.getId();

        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
            dishFlavorService.save(flavor);
        }

        return Result.success("添加成功");
    }

    @Override
    public Result updateSingle(DishDto dishDto) {

        //修改dishService
        boolean r1 = dishService.updateById(dishDto);

        //获取dishServiceId
        Long id = dishDto.getId();

        //获取口味列表
        List<DishFlavor> flavors = dishDto.getFlavors();

        //先将原来的口味删除,在添加新的口味
        LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId, id);
        dishFlavorService.remove(lqw);

        //将菜品值设置给口味,保存口味
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(id);
            dishFlavorService.save(flavor);
        }

        return Result.success("修改成功");
    }


}
